<!-- 档案分类 -->
<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
    >
      <el-form-item label="分类名称" prop="typeName">
        <el-input
          v-model.trim="queryParams.typeName"
          placeholder="请输入分类名称"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="分类编号" prop="typeId">
        <el-input
          v-model.trim="queryParams.typeId"
          placeholder="请输入分类编号"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="所属部门" prop="deptId" v-if="isAdmin">
        <el-select v-model.trim="queryParams.deptId" filterable clearable placeholder="请选择">
          <el-option
            v-for="item in deptOptions"
            v-if="item.ancestors !== first_leve && item.ancestors != second_leve"
            :key="item.deptId"
            :label="item.deptName"
            :value="item.deptId"
            :disabled="item.status == 1"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model.trim="queryParams.status" placeholder="部门状态" clearable size="small">
          <el-option
            v-for="dict in dict.type.sys_normal_disable"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:type:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="info" plain icon="el-icon-sort" size="mini" @click="toggleExpandAll">展开/折叠</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="info"
          plain
          icon="el-icon-upload2"
          size="mini"
          @click="handleImport"
          v-hasPermi="['system:type:importData']"
        >导入</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-edit"
          size="mini"
          @click="handleExport"
          v-hasPermi="['system:type:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table
      border
      v-if="refreshTable"
      v-loading="loading"
      :data="typeList"
      row-key="typeId"
      :default-expand-all="isExpandAll"
      :tree-props="{children: 'children', hasChildren: 'hasChildren'}"
    >
      <el-table-column label="分类名称" prop="typeName" min-width="150px" show-overflow-tooltip />
      <el-table-column label="分类编号" align="center" prop="typeId" />
      <el-table-column label="显示顺序" align="center" prop="orderNum" min-width="50px" />
      <el-table-column label="分类描述" align="center" prop="typeDescribe" />
      <el-table-column label="是否建表" prop="isCustom" width="80">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.tbFlag === '1'">是</el-tag>
          <el-tag type="info" v-if="scope.row.tbFlag === '0'">否</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="status" label="状态" width="70">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.sys_normal_disable" :value="scope.row.status" />
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="180">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:type:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-plus"
            @click="handleAdd(scope.row)"
            v-hasPermi="['system:type:add']"
          >新增</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:type:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 添加或修改档案分类对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="600px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-row>
          <el-col :span="24">
            <el-form-item label="上级分类" prop="parentId">
              <treeselect
                v-model.trim="form.parentId"
                :options="typeOptions"
                :normalizer="normalizer"
                :show-count="true"
                placeholder="选择上级分类"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="分类名称" prop="typeName">
              <el-input v-model.trim="form.typeName" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="显示排序" prop="orderNum">
              <el-input-number v-model.trim="form.orderNum" controls-position="right" :min="0" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="所属部门">
              <el-select v-model.trim="form.deptIds" multiple placeholder="请选择">
                <el-option
                  v-for="item in deptOptions"
                  v-if="item.ancestors !== first_leve && item.ancestors != second_leve"
                  :key="item.deptId"
                  :label="item.deptName"
                  :value="item.deptId"
                  :disabled="item.status == 1"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="分类编号" prop="typeId">
              <el-input v-model.trim="form.typeId" :readonly="code_rdonly" placeholder="请输分类编号" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="分类描述" prop="typeDescribe">
              <el-input v-model="form.typeDescribe" type="textarea" placeholder="请输入内容" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="是否建表">
              <el-radio-group v-model.trim="form.tbFlag">
                <el-radio label="0">否</el-radio>
                <el-radio label="1">是</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="状态">
              <el-radio-group v-model.trim="form.status">
                <el-radio
                  v-for="dict in dict.type.sys_normal_disable"
                  :key="dict.value"
                  :label="dict.value"
                >{{dict.label}}</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <!-- 档案类型导入对话框 -->
    <el-dialog :title="upload.title" :visible.sync="upload.open" width="400px" append-to-body>
      <el-upload
        ref="upload"
        :limit="1"
        accept=".xlsx, .xls"
        :headers="upload.headers"
        :action="upload.url"
        :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :auto-upload="false"
        :data="upload.data"
        drag
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">
          将文件拖到此处，或
          <em>点击上传</em>
        </div>
        <div class="el-upload__tip text-center" slot="tip">
          <span>仅允许导入xls、xlsx格式文件。</span>
          <el-link
            type="primary"
            :underline="false"
            style="font-size: 12px; vertical-align: baseline"
            @click="importTemplate"
            v-hasPermi="['system:type:importTemplate']"
          >下载模板</el-link>
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listType,
  getType,
  delType,
  addType,
  updateType
} from "@/api/system/type";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import { listDept } from "@/api/system/dept";
import { getToken } from "@/utils/auth";

export default {
  name: "Type",
  dicts: ["sys_normal_disable"],
  components: {
    Treeselect
  },
  data() {
    return {
      // 祖籍菜单：first_leve顶级, second_leve第二级，
      first_leve: "0",
      second_leve: "0,100",
      // 遮罩层
      loading: true,
      // 显示搜索条件
      showSearch: true,
      // 档案分类表格数据
      typeList: [],
      // 档案分类树选项
      typeOptions: [],
      // 部门选项
      deptOptions: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 是否展开，默认全部展开
      isExpandAll: false,
      // 重新渲染表格状态
      refreshTable: true,
      // 判断提交类型。0：修改， 1：新增
      subType: null,
      // 判断是否超级管理员
      isAdmin: false,
      // 分类编号只读
      code_rdonly: false,
      // 查询参数
      queryParams: {
        typeName: null,
        status: null,
        deptId: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        parentId: [
          { required: true, message: "上级分类不能为空", trigger: "blur" }
        ],
        typeName: [
          { required: true, message: "分类名称不能为空", trigger: "blur" }
        ],
        orderNum: [
          { required: true, message: "显示顺序不能为空", trigger: "blur" }
        ],
        typeId: [
          { required: true, message: "分类编号不能为空", trigger: "blur" }
        ]
      },
      // 导入参数
      upload: {
        // 是否显示弹出层
        open: false,
        // 弹出层标题
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/system/type/importData",
        // 上传参数
        data: {}
      }
    };
  },
  created() {
    this.getList();
    this.getTreeselectDept();
    // 判断是否超级管理员或管理员
    this.getIsAdmin().then(res => {
      this.isAdmin = res;
    })
  },
  methods: {
    /** 查询档案分类列表 */
    getList() {
      this.loading = true;
      listType(this.queryParams).then(response => {
        this.typeList = this.handleTree(response.data, "typeId", "parentId");
        this.loading = false;
      });
    },
    /** 转换档案分类数据结构 */
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children;
      }
      return {
        id: node.typeId,
        label: node.typeName,
        children: node.children
      };
    },
    /** 查询档案分类下拉树结构 */
    getTreeselect() {
      listType().then(response => {
        this.typeOptions = [];
        const data = { typeId: 0, typeName: "顶级节点", children: [] };
        // typeId, parentId 参数挂接树形数据
        data.children = this.handleTree(response.data, "typeId", "parentId");
        this.typeOptions.push(data);
      });
    },
    /** 查询部门下拉树结构 */
    getTreeselectDept() {
      listDept().then(response => {
        this.deptOptions = response.data;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        typeId: null,
        parentId: null,
        ancestors: null,
        typeName: null,
        orderNum: null,
        typeDescribe: null,
        status: "0",
        tbFlag: "0",
        deptIds: [],
        delFlag: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 新增按钮操作 */
    handleAdd(row) {
      console.log(row)
      this.reset();
      this.code_rdonly = false;
      this.subType = 1;
      if (row != undefined) {
        this.form.parentId = row.typeId;
      }
      this.getTreeselect();
      this.open = true;
      this.title = "添加档案分类";
    },
    /** 展开/折叠操作 */
    toggleExpandAll() {
      this.refreshTable = false;
      this.isExpandAll = !this.isExpandAll;
      this.$nextTick(() => {
        this.refreshTable = true;
      });
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.code_rdonly = true;
      this.subType = 0;
      this.reset();
      this.getTreeselect();
      if (row != null) {
        this.form.parentId = row.typeId;
      }
      getType(row.typeId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改档案分类";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.subType == 0) {
            //subType: 0 修改
            updateType(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.subType = null; // 重置判断状态
              this.getList();
            });
          } else if (this.subType == 1) {
            //subType: 1 修改
            addType(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.subType = null; // 重置判断状态
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      this.$modal
        .confirm('是否确认删除档案分类编号为"' + row.typeId + '"的数据项？')
        .then(function() {
          return delType(row.typeId);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
    /** 下载模板操作 */
    importTemplate() {
      this.download(
        "system/type/importTemplate",
        {},
        `type_template_${new Date().getTime()}.xlsx`
      );
    },
    /** 导入按钮操作 */
    handleImport() {
      this.upload.title = "档案类型导入";
      this.upload.open = true;
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "system/type/export",
        {},
        `type_${new Date().getTime()}.xlsx`
      );
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false;
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      this.$alert(
        "<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" +
          response.msg +
          "</div>",
        "导入结果",
        { dangerouslyUseHTMLString: true }
      );
      this.getListArch();
    },
    // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit();
    }
  }
};
</script>
